<?php

namespace app\api\controller;

use app\admin\model\articel\Article as ArticleModel;
use app\admin\model\Company;
use app\admin\model\service\Agent;
use app\api\service\EasywechatService;
use app\api\service\OfficialAccountService;
use app\api\service\ThrowNewErr;
use app\common\controller\Api;
use app\common\library\Auth;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\library\Token;
use app\common\service\ALiSendService;
use fast\Random;
use think\Cache;
use think\Config;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Validate;
use app\common\model\User as UserModel;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third', 'getUserToken', 'mpLogin', 'sendSms','phoneLogin'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $phone 账号
     * @param string $password 密码
     */
    public function login()
    {
        $phone = $this->request->post('mobile');
        $password = $this->request->post('password');
        $type = $this->request->post('type',1);

        if (!$phone || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $user = UserModel::getByMobile($phone);
        if (!isset($user)) {
            $this->error("用户不存在");
        }
        if($type!= 1){
            $token = $this->request->param("temporary_token", "");
            if ($token == "" && $type== 1) {
                $this->error('请传temporary_token');
            }
            $openId = Cache::get($token);
            if (!$openId) {
                $this->error('temporary_token失效了');
            }

            if ($user->openid == "") {
                $user->openid = $openId;
                $user->save();
            }
        }

        $ret = $this->auth->login($user->username, $password);
        if ($ret) {

            Cache::rm($token);
            if($type== 1){
                Cache::rm($openId);
            }

            $uid=$user['id'];
            $token = Random::uuid();
            Token::set($token,$uid, 3600);
            $retunData = [
                'token' => $token,
                'userInfo' => $this->userInfo($uid)
            ];
            $this->success(__('Logged in successful'), $retunData);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function mobilelogins()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email 邮箱
     * @param string $mobile 手机号
     * @param string $code 邀请码
     */
    public function register()
    {
        $password = $this->request->post('password');
        $mobile = $this->request->post('phone');
        $code = $this->request->post('code');
        $openid = $this->request->post('openid');
        $username = $mobile;
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = null;
        Db::startTrans();
        try {
            //是否采用模型验证
            $ret = $this->auth->register($username, $password, "", $mobile, []);
            $agent = null;
            if (!empty($code)) {
                $agent = Agent::get(["code" => $code]);
            }
            $userinfo = $this->auth->getUserinfo();
            $companyInfo = ["user_id" => $userinfo["id"]];
            if ($agent) {
                $companyInfo["service_agent_id"] = $agent->id;
            }
            //初始化公司信息
            Company::create($companyInfo);
//            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($ret) {
            $data = ['userinfo' => $userinfo];
            $user = $this->auth->getUser();
            $user->openid = $openid;
            $user->save();
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar 头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio 个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $mobile = $this->request->post('mobile');
        $email = $this->request->post('email');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        if ($mobile) {
            $exists = \app\common\model\User::where('mobile', $mobile)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Mobile already exists'));
            }
            $user->mobile = $mobile;
        }
        if ($email) {
            $exists = \app\common\model\User::where('email', $email)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Email already exists'));
            }
            $user->email = $email;
        }
        if (!str_starts_with($avatar, "data")) {
            $user->avatar = $avatar;
        }
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email 邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo' => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $newpassword 新密码
     * @param string $captcha 验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 根据code获取token
     * @author: zhaoyu
     * @Time: 2024/1/19 23:40
     */
    public function getUserToken()
    {
        $code = $this->request->post("code", "");
        $type= $this->request->post('type',1);
        if ( $type ==1 &&  $code == "") {
            $this->error('请传code码');
        }
        if($type == 1 ){
            $easyWeicahtService = new EasywechatService();
            $open = $easyWeicahtService->loginCode($code);
            $token = Cache::get($open['openid']);
            if (!$token) {
                $token = getRandChars(32);
            }
            Cache::set($open['openid'], $token, 72000);
            Cache::set($token, $open['openid'], 72000);//反过来设置
            $this->success("获取token成功", ['temporary_token' => $token]);
        }else{
            $token = getRandChars(32);
            $this->success("获取token成功", ['temporary_token' => $token]);
        }

    }


    /**小程序登录返回token
     * @throws PDOException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author: zhaoyu
     * @Time: 2024/1/20 13:32
     */
    public function mpLogin()
    {
        if ($this->request->isPost() == false) {
            $this->error('请求方式错误');
        }
        $code = $this->request->post("code", "");
        if ($code == "") {
            $this->error('请传code码');
        };
        $token = $this->request->param("temporary_token", "");
        if ($token == "") {
            $this->error('请传temporary_token');
        }
        $openId = Cache::get($token);
        if (!$openId) {
            $this->error('temporary_token失效了');
        }
        $invite_code = $this->request->post("invite_code", "");
        $spread_uid = $this->request->post("spread_uid", 0);
//        if (!empty($invite_code) && !empty($spread_uid)) {
//            $this->error('邀请ID和邀请码不能存在');
//        }
        $easyWeicahtService = new OfficialAccountService();
        $phone = $easyWeicahtService->getPhoneNumber($code);
        $userModel = new UserModel();
        $user = $userModel->where(['openid' => $openId])->find();
        $ip = request()->ip();
        $time = time();
        $userMobile = $userModel->where(['mobile' => $phone])->find();
        if ($user) {
            if ($user['mobile'] && $user['mobile'] != $phone) {
                $this->error("和已经存在不一致");
            }
            $uid = $user['id'];
            $updateData = [
                'logintime' => $time,
                'loginip' => $ip,
                'updatetime' => $time,
            ];
            Db::table('zwa_user')->where(['id' => $uid])->update($updateData);
        } else {
            if ($userMobile) {
                $uid = $userMobile['id'];
//                $this->error('该手机号用户');  //应该并到一起去
                $updateData = [
                    'logintime' => $time,
                    'loginip' => $ip,
                    'openid' => $openId,
                    'updatetime' => $time,
                ];
                Db::table('zwa_user')->where(['id' => $uid])->update($updateData);

            } else {
                if ($invite_code != '') {
                    $inviteUser = $userModel->where(['invite_code' => $invite_code])->find();
                    $spread_uid = $inviteUser['id'] ?? 0;
                }
                $username = $phone;
                $salt = Random::alnum();
                $password = (new Auth())->getEncryptPassword('32Aa21', $salt);

                $insertData = [
                    'username' => $username,
                    'mobile' => $phone,
                    'nickname' => preg_match("/^1[3-9]{1}\d{9}$/", $username) ? substr_replace($username, '****', 3, 4) : $username,
                    'salt' => $salt,
                    'password' => $password,
                    'jointime' => $time,
                    'joinip' => $ip,
                    'logintime' => $time,
                    'loginip' => $ip,
                    'prevtime' => $time,
                    'status' => 'normal',
                    'group_id' => 0,
                    'invite_code' => $salt,
                    'spread_uid' => $spread_uid,
                    'openid' => $openId,
                    'createtime' => $time,
                    'updatetime' => $time,
                ];
                $uid = Db::table('zwa_user')->insertGetId($insertData);

//                if($spread_uid > 0){
//                    //TODO
//                }
            }

        }
        Cache::rm($token);
        Cache::rm($openId);
        $token = Random::uuid();
        Token::set($token, $uid, 172800);
        $retunData = [
            'token' => $token,
            'userInfo' => $this->userInfo($uid)
        ];
        $this->success("登录成功", $retunData);
    }

    /**短信验证码
     * @author: zhaoyu
     * @Time: 2024/1/20 19:34
     */
    public function sendSms()
    {
        $mobile = $this->request->post('mobile');
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }

        //应该是缓存
        $sendDervice = new ALiSendService();
        $sendDervice->main($mobile);
        $this->success("获取成功");

    }


    /**小程序手机号登录
     * @throws PDOException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author: zhaoyu
     * @Time: 2024/3/11 10:26
     */
    public function phoneLogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        $token = $this->request->param("temporary_token", "");
        $loginType = $this->request->param("type", 1);
        if ($token == "") {
            $this->error('请传temporary_token');
        }
        $invite_code = $this->request->post("invite_code", "");
        $spread_uid = $this->request->post("spread_uid", 0);

        if (!$mobile || !$captcha ) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $openId = Cache::get($token);
        if (!$openId && $loginType ==1) {
            $this->error('temporary_token失效了');
        }

        //现在就直接验证码
//        $cache= Cache::get($mobile);
//        if($cache!= $captcha){
//            $this->error(__('Captcha is incorrect'));
//        }

        if($loginType==1){
            $userModel = new UserModel();
            $user = $userModel->where(['openid' => $openId])->find();
            $ip = request()->ip();
            $time = time();
            $userMobile = $userModel->where(['mobile' => $mobile])->find();
            if ($user) {
                if ($user['mobile'] && $user['mobile'] != $mobile) {
                    $this->error("已经存在该用户了");
                }
                $uid = $user['id'];
                $updateData = [
                    'logintime' => $time,
                    'loginip' => $ip,
                    'updatetime' => $time,
                ];
                Db::table('zwa_user')->where(['id' => $uid])->update($updateData);
            } else {
                if ($userMobile) {
                    $uid = $userMobile['id'];
//                $this->error('该手机号用户');  //应该并到一起去
                    $updateData = [
                        'logintime' => $time,
                        'loginip' => $ip,
                        'openid' => $openId,
                        'updatetime' => $time,
                    ];
                    Db::table('zwa_user')->where(['id' => $uid])->update($updateData);

                } else {
                    if ($invite_code != '') {
                        $inviteUser = $userModel->where(['invite_code' => $invite_code])->find();
                        $spread_uid = $inviteUser['id'] ?? 0;
                    }
                    $username = $mobile;
                    $salt = Random::alnum();
                    $password = (new Auth())->getEncryptPassword('32Aa21', $salt);

                    $insertData = [
                        'username' => $username,
                        'mobile' => $mobile,
                        'nickname' => preg_match("/^1[3-9]{1}\d{9}$/", $username) ? substr_replace($username, '****', 3, 4) : $username,
                        'salt' => $salt,
                        'password' => $password,
                        'jointime' => $time,
                        'joinip' => $ip,
                        'logintime' => $time,
                        'loginip' => $ip,
                        'prevtime' => $time,
                        'status' => 'normal',
                        'group_id' => 0,
                        'invite_code' => $salt,
                        'spread_uid' => $spread_uid,
                        'openid' => $openId,
                        'createtime' => $time,
                        'updatetime' => $time,
                    ];
                    $uid = Db::table('zwa_user')->insertGetId($insertData);

//                if($spread_uid > 0){
//                    //TODO
//                }
                }

            }
            Cache::rm($token);
            Cache::rm($openId);
            $token = Random::uuid();
            Token::set($token, $uid, 172800);
            $retunData = [
                'token' => $token,
                'userInfo' => $this->userInfo($uid)
            ];
            $this->success("登录成功", $retunData);
        }else{

            $userModel = new UserModel();
            $userMobile = $userModel->where(['mobile' => $mobile])->find();
            $ip = request()->ip();
            $time = time();

            if ($userMobile) {
                $uid = $userMobile['id'];
//                $this->error('该手机号用户');  //应该并到一起去
                $updateData = [
                    'logintime' => $time,
                    'loginip' => $ip,
                    'openid' => $openId,
                    'updatetime' => $time,
                ];
                Db::table('zwa_user')->where(['id' => $uid])->update($updateData);

            } else {
                if ($invite_code != '') {
                    $inviteUser = $userModel->where(['invite_code' => $invite_code])->find();
                    $spread_uid = $inviteUser['id'] ?? 0;
                }
                $username = $mobile;
                $salt = Random::alnum();
                $password = (new Auth())->getEncryptPassword('32Aa21', $salt);

                $insertData = [
                    'username' => $username,
                    'mobile' => $mobile,
                    'nickname' => preg_match("/^1[3-9]{1}\d{9}$/", $username) ? substr_replace($username, '****', 3, 4) : $username,
                    'salt' => $salt,
                    'password' => $password,
                    'jointime' => $time,
                    'joinip' => $ip,
                    'logintime' => $time,
                    'loginip' => $ip,
                    'prevtime' => $time,
                    'status' => 'normal',
                    'group_id' => 0,
                    'invite_code' => $salt,
                    'spread_uid' => $spread_uid,
                    'createtime' => $time,
                    'updatetime' => $time,
                ];
                $uid = Db::table('zwa_user')->insertGetId($insertData);


            }
            Cache::rm($token);
            $token = Random::uuid();
            Token::set($token, $uid, 172800);
            $retunData = [
                'token' => $token,
                'userInfo' => $this->userInfo($uid)
            ];
            $this->success("登录成功", $retunData);
        }

    }






    private function userInfo($uid)
    {
        //0cf48445-93f0-4fb5-88fc-49d6e008c374
        $userModel = new UserModel();
        $filed = 'id,group_id,username,nickname,email,mobile,avatar,level,gender,money,score,jointime,createtime,service_agent_id,service_agent_user_id,spread_uid,invite_code';
        $user = $userModel->field($filed)->where(['status' => 'normal'])->with(['company'])->find($uid);
        if (!$user) {
            (new ThrowNewErr())->validateFailException('用户被禁止或者不存在');
        }
        return $user;
    }


    /**获取用户信息
     * @author: zhaoyu
     * @Time: 2024/1/24 17:05
     */
    public function userFileInfo()
    {
        $uid = $this->auth->getUser()->id;
//        $uid=66;
        $user = $this->userInfo($uid);
        $this->success("获取成功", $user);
    }


    //1acd3690-ffc0-440e-a1c6-1f8039fabb82
    public  function  userLikeAction(){
        if($this->request->isPost() == false){
            $this->error('请求方式不对');
        }
        $goods_id = $this->request->post('goods_id');
        if(!$goods_id){
            $this->error('商品ID不能为空');
        }
        $uid= $this->auth->getUser()->id;

        $goodsLike= Db::name('goods_likes')->where(['uid'=>$uid,'goods_id'=>$goods_id])->find();
        if($goodsLike){
            Db::name('goods_likes')->where(['uid'=>$uid,'goods_id'=>$goods_id])->delete();
        }else{
            Db::name('goods_likes')->insert([
                'uid'=>$uid,
                'goods_id'=>$goods_id,
                'create_time'=>time()
            ]);
        }
        $this->success('操作成功');

    }

    public  function  userLikeLists(){
//        if($this->request->isPost() == false){
//            $this->error('请求方式不对');
//        }
//        $goods_id = $this->request->post('goods_id');
//        if(!$goods_id){
//            $this->error('商品ID不能为空');
//        }
//        $uid= $this->auth->getUser()->id;
//
//        $goodsLike= Db::name('goods_likes')->where(['uid'=>$uid,'goods_id'=>$goods_id])->find();
//        if($goodsLike){
//            Db::name('goods_likes')->where(['uid'=>$uid,'goods_id'=>$goods_id])->delete();
//        }else{
//            Db::name('goods_likes')->insert([
//                'uid'=>$uid,
//                'goods_id'=>$goods_id,
//                'create_time'=>time()
//            ]);
//        }
//        $this->success('操作成功');

        $uid= $this->auth->getUser()->id;

//        $params =$this->request->param();

        $list = Db::name('goods_likes')
            ->alias('gl')
            ->join('goods g','g.id = gl.goods_id')
            ->where(['gl.uid'=>$uid])->order("gl.id", "desc")
            ->field('gl.*,g.title,g.goods_desc,g.image')
            ->paginate($this->request->param('list_rows', 10));;
            $list->each(function ($item){
                $item['create_time']= date('Y-m-d H:i:s',time());
                return $item;
            });
        $this->success("success", $list);

    }


    /**
     * 检测报告
     * @throws \think\exception\DbException
     * @author: zhaoyu
     * @Time: 2024/1/26 11:53
     */
    public  function  reports(){
        $uid= $this->auth->getUser()->id;

//        $params =$this->request->param();
        $list = Db::name('report')
            ->alias('r')
            ->join('order o','o.id = r.order_id')
            ->where(['r.uid'=>$uid,'r.status'=>2])->order("r.id", "desc")
            ->field('r.*,o.name,o.order_no')
            ->paginate($this->request->param('list_rows', 10));;
        $list->each(function ($item){
            $item['create_time']= date('Y-m-d H:i:s',time());
            unset($item['env_images']);
            return $item;
        });
        $this->success("success", $list);
    }
    public  function  certificate(){
        $uid= $this->auth->getUser()->id;

//        $params =$this->request->param();
        $list = Db::name('certificate')
            ->alias('r')
            ->join('order o','o.id = r.order_id')
            ->where(['r.user_id'=>$uid,'r.status'=>2])->order("r.id", "desc")
            ->field('r.*,o.name,o.order_no')
            ->paginate($this->request->param('list_rows', 10));;
        $list->each(function ($item){
            $item['create_time']= date('Y-m-d H:i:s',time());
            return $item;
        });
        $this->success("success", $list);
    }

}
